package com.pingancar.creditmanage.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pingancar.creditmanage.dao.*;
import com.pingancar.creditmanage.pojo.*;
import com.pingancar.creditmanage.util.HttpHelper;
import com.pingancar.creditmanage.util.JSONReceiver;
import com.pingancar.creditmanage.util.LBSMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2014/9/6 0006.
 */
@Service
public class AdminServiceImpl {
    @Autowired
    private AdminDaoImpl adminDao;
    @Autowired
    private CashDaoImpl cashDao;
    @Autowired
    private ShopInfoDaoImpl shopInfoDao;
    @Autowired
    private ShopUserDaoImpl shopUserDao;
    @Autowired
    private ServicetypeDaoImpl servicetypeDao;
    @Autowired
    private PAServiceDaoImpl paServiceDao;
    @Autowired
    private FeedbackDaoImpl feedbackDao;

    public AdminPojo login(AdminPojo adminPojo) {
        //密码不能小于6位
        if(adminPojo.getPasswd().length()<6){
            return null;
        }
        //用户名不能小于4位
        if(adminPojo.getUsername().length()<4){
            return null;
        }
        //检验是否存在非法字符
        String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern p = Pattern.compile(regEx);
        if(p.matcher(adminPojo.getPasswd()).find()||p.matcher(adminPojo.getUsername()).find()){
            return null;
        }
        List<AdminPojo> result=adminDao.findByProperty("username", adminPojo.getUsername());
        //没有该用户
        if(result == null || result.isEmpty()){
            return null;
        }
        // 密码验证
        if(result.get(0).getPasswd().equals(adminPojo.getPasswd())){
            return result.get(0);
        }

        return null;
    }

    /**
     * 获取提现列表
     * @param offset
     * @param len
     * @param cashed
     * @return
     */
    public List cashlist(Integer offset, Integer len, boolean cashed) {
        return cashDao.cashlist(offset, len, cashed);
    }

    public Long countOfCashlist(boolean cashed) {
        return cashDao.countOfCashlist(cashed);
    }

    /**
     * 确认提现
     * @param adminPojo
     * @param id
     * @return
     */
    public boolean confirmCash(AdminPojo adminPojo, Integer id) {
        adminPojo = adminDao.load(adminPojo.getId());
        if (adminPojo == null || id == null) {
            return false;
        }

        CashPojo cashPojo = cashDao.load(id);
        if (cashPojo == null)
            return false;

        cashPojo.setAdmin(adminPojo);
        cashPojo.setConfirmtime(new Timestamp(new Date().getTime()));
        cashDao.update(cashPojo);

        return true;
    }

    /**
     * 添加商家
     * @param name
     * @param username
     * @param description
     * @param location
     * @param bh
     * @return
     */
    public boolean addShop(String name, String username, String description, String con, String location,
                           String bh, Double xpos, Double ypos) {
        List l = shopInfoDao.findByProperty("name", name);
        if (l!=null && !l.isEmpty())
            return false;
        l = shopUserDao.findByProperty("username", username);
        if (l!=null && !l.isEmpty())
            return false;

        ShopinfoPojo shopinfoPojo = new ShopinfoPojo();
        shopinfoPojo.setName(name);
        shopinfoPojo.setCon(con);
        shopinfoPojo.setLocation(location);
        shopinfoPojo.setDescription(description);
        shopinfoPojo.setBh(bh);
        shopinfoPojo.setXpos(xpos);
        shopinfoPojo.setYpos(ypos);
        shopinfoPojo.setOrdersum(0);
        shopinfoPojo.setStarsum(0);
        shopinfoPojo.setRatesum(0);
        shopinfoPojo.setStatus(0);
        shopinfoPojo.setCredit(0);
        shopinfoPojo.setLbs(0);
        shopinfoPojo.setShopid("111");

        shopInfoDao.save(shopinfoPojo);

        //lbs云数据保存
        LBSMessage lbsMessage = new LBSMessage();
        lbsMessage.setCoord_type(3);
        lbsMessage.setAddress(location);
        lbsMessage.setLongitude(xpos);
        lbsMessage.setLatitude(ypos);
        lbsMessage.setTitle(name);
        lbsMessage.setTags("-1");
        lbsMessage.setShopid(shopinfoPojo.getId());

        JSONReceiver jsonReceiver = JSONReceiver.createPOI(lbsMessage);
        if (jsonReceiver != null) {
            shopinfoPojo.setLbs(jsonReceiver.getId());
            shopInfoDao.update(shopinfoPojo);
        }

        ShopuserPojo shopuserPojo = new ShopuserPojo();
        shopuserPojo.setUsername(username);
        shopuserPojo.setPasswd("123456");
        shopuserPojo.setMain(1);
        shopuserPojo.setShopinfo(shopinfoPojo);

        shopUserDao.save(shopuserPojo);

        return true;
    }

    public boolean modifyShop(ShopinfoPojo shopinfoPojo) {
        if (shopinfoPojo == null)
            return false;

        ShopinfoPojo shop = shopInfoDao.load(shopinfoPojo.getId());
        if (shop == null)
            return false;

        if (!shop.getName().equals(shopinfoPojo.getName())) {
            List l = shopInfoDao.findByProperty("name", shopinfoPojo.getName());
            if (l != null && !l.isEmpty())
                return false;
        }

        shop.setCon(shopinfoPojo.getCon());
        shop.setBh(shopinfoPojo.getBh());
        shop.setDescription(shopinfoPojo.getDescription());
        shop.setLocation(shopinfoPojo.getLocation());
        shop.setName(shopinfoPojo.getName());
        shop.setXpos(shopinfoPojo.getXpos());
        shop.setYpos(shopinfoPojo.getYpos());

        shopInfoDao.update(shop);

        //lbs修改
        LBSMessage lbsMessage = new LBSMessage();
        lbsMessage.setTitle(shop.getName());
        lbsMessage.setLongitude(shop.getXpos());
        lbsMessage.setLatitude(shop.getYpos());
        lbsMessage.setCoord_type(3);
        lbsMessage.setAddress(shop.getLocation());
        lbsMessage.setId(shop.getLbs());
        JSONReceiver.updataPOI(lbsMessage);

        return true;
    }

    public PaservicePojo addService(Integer shopid, String tag1, Integer creditcost, Integer type) {
        PaservicePojo paservicePojo = new PaservicePojo();
        if (shopid == null)
            return null;
        ShopinfoPojo shopinfoPojo = shopInfoDao.load(shopid);
        if (shopinfoPojo == null)
            return null;

        ServicetypePojo servicetypePojo = servicetypeDao.load(type);
        if (servicetypePojo == null)
            return null;

        paservicePojo.setShopinfo(shopinfoPojo);
        paservicePojo.setTag1(tag1);
        paservicePojo.setAmount(100);
        paservicePojo.setLeftnum(100);
        paservicePojo.setCreditcost(creditcost);
        paservicePojo.setPaserviceid("111");
        paservicePojo.setType(servicetypePojo);

        paServiceDao.save(paservicePojo);

        JSONReceiver jsonReceiver = JSONReceiver.findById(shopinfoPojo.getLbs());
        if (jsonReceiver != null && jsonReceiver.getPoi() != null) {
            String tags = jsonReceiver.getPoi().getTags();
            String new_tags = paServiceDao.checkAddTag(tags, type);
            if (!new_tags.equals(tags)) {
                LBSMessage lbsMessage = new LBSMessage();
                lbsMessage.setId(shopinfoPojo.getLbs());
                lbsMessage.setCoord_type(3);
                lbsMessage.setTags(new_tags);
                JSONReceiver.updataPOI(lbsMessage);
            }
        }

        return paservicePojo;
    }

    public PaservicePojo modifyService(Integer id, String tag1, Integer creditcost, Integer type) {
        PaservicePojo paservicePojo = paServiceDao.load(id);
        if (paservicePojo == null)
            return null;
        ShopinfoPojo shopinfoPojo = paservicePojo.getShopinfo();
        if (shopinfoPojo == null)
            return null;

        Integer old_type = paservicePojo.getType().getId();
        boolean diff_type = (old_type != type);

        if (diff_type) {
            ServicetypePojo servicetypePojo = servicetypeDao.load(type);
            if (servicetypePojo == null)
                return null;
            paservicePojo.setType(servicetypePojo);
        }

        paservicePojo.setTag1(tag1);
        paservicePojo.setCreditcost(creditcost);

        paServiceDao.update(paservicePojo);

        //更改了服务类型可能需要更新lbs数据
        if (diff_type) {
            JSONReceiver jsonReceiver = JSONReceiver.findById(paservicePojo.getShopinfo().getLbs());
            if (jsonReceiver!=null && jsonReceiver.getPoi()!=null) {
                String tags = jsonReceiver.getPoi().getTags();
                String new_tags = paServiceDao.checkAddTag(tags, type);
                new_tags = paServiceDao.checkRemoveTag(new_tags, old_type, shopinfoPojo.getId());


                if (!new_tags.equals(tags)) {

                    LBSMessage lbsMessage = new LBSMessage();
                    lbsMessage.setTags(new_tags);
                    lbsMessage.setId(shopinfoPojo.getLbs());
                    lbsMessage.setCoord_type(3);
                    JSONReceiver.updataPOI(lbsMessage);
                }
            }
        }

        return paservicePojo;
    }

    public PaservicePojo stopService(Integer id) {
        PaservicePojo paservicePojo = paServiceDao.load(id);
        if (paservicePojo == null)
            return null;
        ShopinfoPojo shopinfoPojo = paservicePojo.getShopinfo();
        if (shopinfoPojo == null)
            return null;

        paservicePojo.setStop(1);
        paServiceDao.update(paservicePojo);

        JSONReceiver jsonReceiver = JSONReceiver.findById(shopinfoPojo.getLbs());
        if (jsonReceiver!=null && jsonReceiver.getPoi()!=null) {
            String tags = jsonReceiver.getPoi().getTags();
            String new_tags = paServiceDao.checkRemoveTag(tags, paservicePojo.getType().getId(), shopinfoPojo.getId());
            if (!new_tags.equals(tags)) {
                LBSMessage lbsMessage = new LBSMessage();
                lbsMessage.setId(shopinfoPojo.getLbs());
                lbsMessage.setCoord_type(3);
                lbsMessage.setTags(new_tags);
                JSONReceiver.updataPOI(lbsMessage);
            }
        }

        return paservicePojo;
    }

    public boolean modifyPassword(AdminPojo adminPojo, String oldpw, String newpw) {
        adminPojo = adminDao.load(adminPojo.getId());
        if (adminPojo==null)
            return false;

        if (!adminPojo.getPasswd().equals(oldpw))
            return false;

        //密码不能小于6位
        if(newpw.length()<6){
            return false;
        }

        //检验是否存在非法字符
        String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern p = Pattern.compile(regEx);
        if(p.matcher(newpw).find()){
            return false;
        }

        adminPojo.setPasswd(newpw);
        adminDao.update(adminPojo);

        return true;
    }

    public Long countOfFeedbacklist() {
        return feedbackDao.countOfFeedbacklist();
    }

    public List feedbackList(Integer offset, Integer len) {
        return feedbackDao.feedbackList(offset, len);
    }

    public FeedbackPojo feedbackDetail(Integer id) {
        return feedbackDao.load(id);
    }
}

